import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  const userInfo = ref(null)
  const isLoggedIn = ref(false)
  const isAdmin = ref(false)
  const userStatus = ref(0) // 0: 普通用户, 1: 专家, 2: 待审核

  const setUserInfo = (info) => {
    // 转换字段名以匹配前端使用
    const transformedInfo = {
      ...info,
      imageUrl: info.image_url || info.imageUrl,
      callName: info.call_name || info.callName,
      userName: info.user_name || info.userName,
      phoneNumber: info.phone_number || info.phoneNumber
    }
    userInfo.value = transformedInfo
    isLoggedIn.value = true
    // 根据角色和申请状态判断是否为管理员
    isAdmin.value = info.roleId === 1 && info.applyType === 1
    // 设置用户状态
    userStatus.value = info.applyType || 0
    // 确保 userRoles 数组存在
    if (!userInfo.value.userRoles) {
      userInfo.value.userRoles = []
    }
  }

  const clearUserInfo = () => {
    userInfo.value = null
    isLoggedIn.value = false
    isAdmin.value = false
    userStatus.value = 0
  }

  const updateUserStatus = (status) => {
    if (userInfo.value) {
      userInfo.value.applyType = status
    }
  }

  const addUserRole = (role) => {
    if (userInfo.value && userInfo.value.userRoles) {
      userInfo.value.userRoles.push(role)
    }
  }

  return {
    userInfo,
    isLoggedIn,
    isAdmin,
    userStatus,
    setUserInfo,
    clearUserInfo,
    updateUserStatus,
    addUserRole
  }
}) 